import { useRequest } from 'ahooks'
import {
  Button,
  Space,
  Table,
  Tag,
} from 'antd'
import { useCallback, useMemo, useState } from 'react'
import { getAdminUserApi, deleteAdminUserApi } from '../../api/auth'
import DeleteButton from '../../components/DeleteButton'
import AddAdminModle from './AddAdminModle'
import UpdateAdminDrawer from './UpdateAdminDrawer'

const AppAdmin = () => {
  const { data, loading, run: reGetAdminList } = useRequest(getAdminUserApi)
  console.log(data)
  const handleDeleteAdmin = useCallback(async(adminid) => {
    try {
      await deleteAdminUserApi({ adminid })
      reGetAdminList()
    } catch (error) {
      console.log(error)
    }
  }, [])
  // 新增
  const [modleVisible, setMoselvisible] = useState(false)
  const [updataAddminV, setUpdataAddminV] = useState(false)
  const handleShowModle = useCallback((visi, refresh) => {
    setMoselvisible(visi)
    setUpdataAddminV(visi)
    if (refresh) reGetAdminList()
  }, [])

  // 修改信息
  const [dadminname, setAdminid] = useState(null)
  const handleUpdateAdmin = useCallback((name) => {
    setUpdataAddminV(true)
    setAdminid(name)
  }, [dadminname])
  const columns = useMemo(() => ([
    {
      title: 'id',
      dataIndex: 'adminid',
      width: 200,
      ellipsis: true,
    },
    {
      title: '名字',
      dataIndex: 'adminname',
    },
    {
      title: '角色',
      dataIndex: 'role',
      render: (_) => <Tag style={{ color: _ === 1 ? 'purple' : 'orange' }}>{ _ === 1 ? '管理员' : '超级管理员' }</Tag>,
    },
    {
      title: '操作',
      render: (_, record) => (
        <>
          <DeleteButton action={() => handleDeleteAdmin(record.adminid)} />
          <Button onClick={() => handleUpdateAdmin(record.adminname)}>编辑</Button>
        </>
      ),
    },
  ]), [])
  return (
    <Space direction="vertical" style={{ display: 'flex' }}>
      <Button type="primary" onClick={() => setMoselvisible(true)}>新增管理员 </Button>
      <Table
        dataSource={data}
        columns={columns}
        rowKey="adminid"
        loading={loading}
      />
      <AddAdminModle visible={modleVisible} showModel={handleShowModle} />
      <UpdateAdminDrawer visible={updataAddminV} showModel={handleShowModle} adminname={dadminname} />
    </Space>
  )
}
export default AppAdmin
